package com.inoneone.youba.mcht.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.inoneone.youba.mcht.dao.mapper.AnnouncementMapper;
import com.inoneone.youba.mcht.dao.po.*;
import com.inoneone.youba.mcht.dto.PageRsp;
import com.inoneone.youba.mcht.dto.req.*;
import com.inoneone.youba.mcht.dto.rsp.AnnounceDetailRsp;
import com.inoneone.youba.mcht.dto.rsp.AnnounceListRsp;
import com.inoneone.youba.mcht.enums.ErrorCode;
import com.inoneone.toolkit.exception.BusinessRuntimeException;
import com.inoneone.youba.mcht.service.AnnouncementApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AnnouncementApiImpl implements AnnouncementApi {

    @Autowired
    AnnouncementMapper announcementMapper;

    /**
     * Description: 查询公告列表</br>
     * Date: 2017-07-01 22:19:39</br>
     *
     * @param announceListReq
     * @return
     * @author 姬远玄
     * @since JDK 1.7
     */
    @Override
    public PageRsp<AnnounceListRsp> queryAnnounceList(AnnounceListReq announceListReq) {

        //分页查询数据
        PageHelper.startPage(announceListReq.getPageNum(), announceListReq.getPageSize());

        //时间排序
        AnnouncementExample announcementExample = new AnnouncementExample();
        announcementExample.createCriteria().andIsPublicEqualTo(1);
        announcementExample.setOrderByClause("create_time desc");
        List<Announcement> announcements = announcementMapper.selectByExample(announcementExample);
        PageInfo<Announcement> pageCards = new PageInfo<>(announcements);

        //转换输出类
        List<AnnounceListRsp> announcementList = new ArrayList<>();
        for (Announcement announcement : announcements)
        {
            AnnounceListRsp announceListRsp = new AnnounceListRsp();
            BeanUtils.copyProperties(announcement, announceListRsp);
            announcementList.add(announceListRsp);
        }
        PageRsp<AnnounceListRsp> announceListRspPage = new PageRsp<>(pageCards.getTotal(), pageCards.getPageSize(), pageCards.getPageNum(), announcementList);

        return announceListRspPage;    }

    @Override
    public AnnounceDetailRsp queryAnnounceDetail(AnnounceDetailReq announceDetailReq) {
        Announcement result = announcementMapper.selectByPrimaryKey(announceDetailReq.getId());
        if(result == null)
        {
            throw new BusinessRuntimeException(ErrorCode.DATA_EMPTY);
        }
        AnnounceDetailRsp announceDetailRsp = new AnnounceDetailRsp();
        BeanUtils.copyProperties(result, announceDetailRsp);
        return announceDetailRsp;
    }
}
